<?php

// Fixes the encoding to uf8 //$_SESSION['lang']
function SPEC($in_str)
{
  if(!function_exists('mb_detect_encoding')){ return $in_str; }
  $cur_encoding = mb_detect_encoding($in_str) ;
  if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8")){
    return $in_str;
  }elseif(isset($_SESSION['lang']) && $_SESSION['lang'] =="chinese"){
  return mb_convert_encoding($in_str, 'UTF-8','GB2312'); 
  }else{
  return utf8_encode($in_str);
  }  
    
} 

	// checks they are authoized
	function auth_redirect_login() {
		$user = wp_get_current_user();
		if ( $user->id == 0 ) {
			nocache_headers();
			wp_redirect(get_option('siteurl') . '/wp-login.php?redirect_to=' . urlencode($_SERVER['REQUEST_URI']));
			exit();
		}

	}

if(!function_exists("FilterPath")){

	function FilterPath(){
		$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
		$path_parts = pathinfo($path);
		return $path;
	}
}

	function selfURL() {
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$protocol = "http".$s;
		$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
			: (":".$_SERVER["SERVER_PORT"]);
		return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
	}

if(!function_exists("selfURL1")){

	function selfURL1() {
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$protocol = "http".$s;
		$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
			: (":".$_SERVER["SERVER_PORT"]);
		return $protocol."://".$_SERVER['SERVER_NAME'].$port;
	}
}



function ShopperPress_Admin_Cats(){


	$Maincategories= get_categories('use_desc_for_title=1&hide_empty=0&hierarchical=0');
	$Maincatcount = count($Maincategories);	
	
	foreach ($Maincategories as $Maincat) {
		 
		if($Maincat->parent ==0){
		
			print '<input name="cat[]" type="checkbox" value="'.$Maincat->cat_ID.'">' . $Maincat->cat_name."<br />";
			
			// do sub cats
			$currentcat=get_query_var('cat');
			$categories= get_categories('child_of='.$Maincat->cat_ID.'&amp;depth=1&hide_empty=0');
			$catcount = count($categories);		
			$i=1;
				
			if(count($categories) > 0){
				 
				foreach ($categories as $cat) {	
				
					print ' -- <input name="cat[]" type="checkbox" value="'.$cat->cat_ID.'">' . $cat->cat_name . "<br />";
				
				}
			
			}
		
		}	
	}
}

	function multisort($array, $sort_by) {
		foreach ($array as $key => $value) {
			$evalstring = '';
			foreach ($sort_by as $sort_field) {
				$tmp[$sort_field][$key] = $value[$sort_field];
				$evalstring .= '$tmp[\'' . $sort_field . '\'], ';
			}
		}
		$evalstring .= '$array';
		$evalstring = 'array_multisort(' . $evalstring . ');';
		eval($evalstring);
	
		return $array;
	}


	function ShopperPress_Navigation($type=0){

			$catlist=""; $togID=1;
			$SAVED_DISPLAY = get_option("nav_cats");
			$displayCats = "";

			if(!is_array($SAVED_DISPLAY)){ return ""; }

			// BUILT THE SELECTED CATEGORIES
			foreach($SAVED_DISPLAY as $ThisCat){ if($ThisCat['ID'] > 0){
					$displayCats .= $ThisCat['ID'].",";			
			} }				
 
	 		$Maincategories = get_categories('pad_counts=1&use_desc_for_title=1&hide_empty=0&hierarchical=0&include='.$displayCats);
	 		$Maincatcount = count($Maincategories);
			$SHOWRESULTS = multisort( $SAVED_DISPLAY , array('ORDER') );
			foreach($SHOWRESULTS as $ThisCat){ if($ThisCat['ID'] > 0){

			foreach ($Maincategories as $Maincat) {

			if($Maincat->term_id == $ThisCat['ID']) {
		 
				if($Maincat->parent ==0){
				
						if($type ==0){
							$catlist .= '<li>
							<a href="'.get_category_link( $Maincat->term_id ).'" title="'.$Maincat->category_nicename.'"><span>';
							$catlist .= $Maincat->cat_name;
							$catlist .= '</span></a>';
						}elseif($type ==1 ){
							
							if($GLOBALS['shopperpress']['categories_leftmenu'] == "hide"){
							$catlist .= '<h2><span><a href="javascript:void(0);" onclick="toggleLayer(\'topnav_'.$togID.'\');" title="'.$Maincat->category_nicename.'" style="text-decoration:none;">';
							$catlist .= $Maincat->cat_name;
							$catlist .= '</a></span></h2><div style="display:none;" id="topnav_'.$togID.'">'; //
							
							$catlist .= '<li>
							<a href="'.get_category_link( $Maincat->term_id ).'" title="'.$Maincat->category_nicename.'"><span>';
							$catlist .= "All Products";
							$catlist .= '</span></a>';
							
							}else{
							$catlist .= '<h2><span><a href="'.get_category_link( $Maincat->term_id ).'" title="'.$Maincat->category_nicename.'" style="text-decoration:none;">';
							$catlist .= $Maincat->cat_name;
							$catlist .= '</a></span></h2>';
							}
							
						}elseif($type ==2 ){
							
							
							$catlist .= '<h2><span><a href="'.get_category_link( $Maincat->term_id ).'" title="'.$Maincat->category_nicename.'" style="text-decoration:none;">';
							$catlist .= $Maincat->cat_name;
							$catlist .= '</a></span></h2>';
							
						}elseif($type ==3){
	
							$catlist .= '<li><a href="'.get_category_link( $Maincat->term_id ).'" title="'.$Maincat->category_nicename.'"><span>';
							$catlist .= $Maincat->cat_name;
							$catlist .= '</span></a>';		
	
						}elseif($type ==4){
	
							$catlist .= '<h2><span><a href="'.get_category_link( $Maincat->term_id ).'" title="'.$Maincat->category_nicename.'" style="text-decoration:none;">';
							$catlist .= $Maincat->cat_name;
							$catlist .= '</a></span></h2>';	
						}		 
				
						// do sub cats
						$categories= get_categories('parent='.$Maincat->cat_ID.'&depth=1&hide_empty=0&hierarchical=0'); 
						$catcount = count($categories);		
						$i=1;
			
	
						if($type ==4){
						if(count($categories) > 0){
						$catlist .="<select style='margin-bottom:20px; width:200px; font-size:16px;' onChange=\"window.location=this.value;\">";					
						foreach ($categories as $cat) {		
						$catlist .="<option value='".get_category_link( $cat->term_id )."'>".$cat->cat_name."</option>";	
						}
						$catlist .="</select>";	
						}	
						}else{
	
	
						if(count($categories) > 0){
						$catlist .="<ul>";					
							foreach ($categories as $cat) {						
								$catlist .= '<li><a href="'.get_category_link( $cat->term_id ).'">';
								$catlist .= $cat->cat_name;
								$catlist .= '</a>';						
								// CHECK FOR MORE SUB CATEGORIES							 				
								$categories1	= get_categories('parent='.$cat->cat_ID.'&depth=1&hide_empty=0');							 
								$catcount1 		= count($categories1);
								if(count($categories1) > 0){
								$catlist .="<ul>";							
									foreach ($categories1 as $cat1) {	
									$catlist .= '<li><a href="'.get_category_link( $cat1->term_id ).'">';
									$catlist .= $cat1->cat_name;
									$catlist .= '</a> ';
									$catlist .= '</li>';
									}									
								$catlist .="</ul>";							
								}										
							$catlist .= '</li>';
							}					
						 $catlist .= '</ul>';
						}
					}
					$togID++;
					if($type ==1){ if($GLOBALS['shopperpress']['categories_leftmenu'] == "hide" && $type != 2){ $catlist .= '</div></li>'; }else{ $catlist .= '</li>'; } }else{ $catlist .= '</li>'; }
				} 
	 		} 
		}
	 } 
	}


	if(get_option("display_showpages") =="next" && $type ==0){
	
		$MainPages = get_pages("exclude=".get_option("excluded_pages")); //
		$Maincatcount = count($Maincategories);	 
			
		foreach ($MainPages as $MainP) {
		
		$catlist .= '<li><a href="'.get_page_link( $MainP->ID ).'" title="'.$MainP->post_title.'"><span>';
								$catlist .= $MainP->post_title;
								$catlist .= '</span></a></li>';
		}
	
	}
	return $catlist;
	
	}
	
	
function shopperpress_sendmail($to, $subject, $message=""){
			
			$headers = 'From: '.get_option("shipping_email").'' . "\r\n" .
					'Reply-To: '.get_option("shipping_email").'' . "\r\n" .
					'X-Mailer: PHP/' . phpversion();
	
			// To send HTML mail, the Content-type header must be set
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	
			if(get_option("shipping_ccemail") !=""){
				$headers .= 'Cc: '.get_option("shipping_ccemail").'' . "\r\n";
			}
			if(get_option("shipping_bccemail") !=""){
				$headers .= 'Bcc: '.get_option("shipping_bccemail").'' . "\r\n";
			}
				
			wp_mail( $to, $subject, $message, $headers);

}


function shopperpress_getcat($req){

	global $wpdb; $catID=0;

	if(isset($req['cat'])){

	$catID = $req['cat'];

	}else{

	$catName = explode("category/",$_SERVER["REQUEST_URI"]);
	$catName1 = explode("/",$catName[1]);

	if(isset($catName1[1])){

		$result = mysql_query("SELECT term_id FROM $wpdb->terms WHERE slug= ('".strip_tags($catName1[1])."' ) LIMIT 1", $wpdb->dbh) 
		or die(mysql_error().' on line: '.__LINE__);
		$array = mysql_fetch_assoc($result);
		if ( is_numeric($array['term_id']) ){
		$catID = $array['term_id'];
		}
	
	}
	
	if(isset($catName1[0]) && $catID==0){

		$result = mysql_query("SELECT term_id FROM $wpdb->terms WHERE slug= ('".strip_tags($catName1[0])."' ) LIMIT 1", $wpdb->dbh) 
		or die(mysql_error().' on line: '.__LINE__);
		$array = mysql_fetch_assoc($result);
		if ( is_numeric($array['term_id']) ){
		$catID = $array['term_id'];
		}
	
	}
 
	}

	if($catID != 0){
		$cat = get_category($catID);
		return $cat;

	}


}





	function shopperpress_banner ($type="top") { 
			
				if(get_option('advertising_'.$type.'_checkbox') !=1){  return "";}
	
				if (get_option('advertising_'.$type.'_adsense') <> "") { 
				
				echo stripslashes(get_option('advertising_'.$type.'_adsense')); 
			
				} else { 
				
					if (!get_option('advertising_'.$type.'_url') || !get_option('advertising_'.$type.'_dest')) {  
					
						 
					 } else { 	
					
						echo '<a href="' . get_option("advertising_".$type."_url") . '" target="_blank"><img src="' . get_option("advertising_".$type."_dest") . '" border="0" /></a>';
						
					} 
				}
	 
	}
	
	
	
	function MakeCurrencyDisplay(){
	
		$CC = array(); $string="";
	
		$CurrencyCode = strip_tags($CurrencyCode);

		// BASE CURRENCY

		$CC['caption'] = get_option("currency_caption");
		$CC['code'] = get_option("currency_code"); 

		$string .='<li><a href="?c='.$CC['code'].'">'.$CC['caption'].'</a></li>';
	 
		for($i=1; $i < 6; $i++){
		
			if( get_option("currency_code_".$i) !=""){		
			
				$CC['caption'] = get_option("currency_caption_".$i);
				$CC['code'] = get_option("currency_code_".$i);

				$string .='<li><a href="?c='.$CC['code'].'">'.$CC['caption'].'</a></li>';
	
			}
		
		}	
		
		return $string;
	
	}
	
		function GetCurrencyExchange($CurrencyCode){

	$CC = array();

	$CurrencyCode = strip_tags($CurrencyCode);
	
	// CHECK THE DEFAULT ONE FIRST
	
	if($CurrencyCode == get_option("currency_code")){
	
			$CC['caption'] = get_option("currency_caption");
			$CC['code'] = get_option("currency_code");
			$CC['symbol'] = get_option("currency_symbol");
			$CC['value'] = get_option("currency_value");
			
			return $CC;
			
	}
 
	for($i=1; $i < 6; $i++){
	 	
		if( $CurrencyCode == get_option("currency_code_".$i)){		
		
			$CC['caption'] = get_option("currency_caption_".$i);
			$CC['code'] = get_option("currency_code_".$i);
			$CC['symbol'] = get_option("currency_symbol_".$i);
			$CC['value'] = get_option("currency_value_".$i);

		}
	
	}	
	
	return $CC;

	}
	
	
	
		function shopperPress_featured($NumberOfPosts = 1, $orderby="rand") {
	
	    global $wpdb; $i=1;
		
		if($NumberOfPosts ==""){ $NumberOfPosts=5; }
 
		$posts = query_posts('&posts_per_page='.$NumberOfPosts.'&orderby='.$orderby.'&meta_key=image&cat='.get_option("article_cats"));
 
		foreach($posts as $thepost) {
 
				$customData[$i]['price'] 		= get_post_meta($thepost->ID, "price", true); 
				$customData[$i]['id'] 			= $thepost->ID;
				$customData[$i]['title'] 		= $thepost->post_title;
				$customData[$i]['description'] 	= $thepost->post_content;
				$customData[$i]['price'] 		= GetPrice(get_post_meta($thepost->ID, "price", true));
				$customData[$i]['old_price'] 	= GetPrice(get_post_meta($thepost->ID, "old_price", true));
				$customData[$i]['price'] 		= GetPrice($customData[$i]['price']);	
				$customData[$i]['image'] 		= get_post_meta($thepost->ID, "thumbnail", true);
	
				if($customData[$i]['image'] ==""){			
					$customData[$i]['image'] = get_post_meta($thepost->ID, "image", true);
				}
				if($customData[$i]['image'] ==""){	
					$customData[$i]['image'] = "wp-content/themes/shopperpress/images/noimg.gif";
				}
	
				$customData[$i]['link'] 		= get_permalink($thepost->ID);
				$i++;
			 
			 }
 
 		wp_reset_query();
		return $customData;
	  

	}
	

?>